import axios from 'axios'
import Utils from '@/utils/util'
import { Notify } from 'vant'
/**
 * config axios
 *
 */
const service = axios.create({
  baseURL: process.env.VUE_APP_BASEURL,
  //baseURL: window.BASE_PASH,
  timeout: 60000 // 请求超时1分钟
})

const keys = {
  "salt": "VURGPMDXuiCNGSNmVjSpInIPZrRZaDzI",
  "pubKey": "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJargA9cpzEikKcY8YWnCcZrF405sPCDQhnHWU4MlUZTdGoaEroa/8iawT0OZhHpRVpV3Iqih52lh+xuVOrWqvMCAwEAAQ==",
  "priKey": "MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAlquAD1ynMSKQpxjxhacJxmsXjTmw8INCGcdZTgyVRlN0ahoSuhr/yJrBPQ5mEelFWlXciqKHnaWH7G5U6taq8wIDAQABAkEAgFeMGQnSfR81WrD7ot57jCHTCQB4gRc96hmOL9a2HRVPYMbPPpRqlXSTU77/mN9vXxUGFT/cDKPjqVZsOn/oyQIhANi7sGoIe+O4bhRYz1X/9UibOUMsaln+yjnPHxLLeEN9AiEAsfe6ntUpp2EOsdVkPha8YkOBXtIGHTXchNu1vinAEy8CICuz1QPciBbIFrJVoiFGRpCIdEh+SUeyX9a+VBa3Hp4FAiBeMN0mv28iVW4vlN9PNT1TTKMmCkaOIzmpX5ebJAGypQIhANijNPMgOyhkdiNZw2iSY7nJakqmxRLeobbaHKhfazHy"
}

/* 请求头类型 */
service.defaults.headers.post['Content-Type'] = 'application/json; charset=UTF-8'

/* 请求拦截 */
service.interceptors.request.use(config => {
  if (config.loading === false) {
    console.log('console1')
  } else {
    config = Object.assign({
      loading: 'body'
    }, config)
  }
  var loginUrl = config.url.indexOf('appLogin') > -1
  if (!loginUrl) {
    //登录接口不需要token
    config.headers['TOKEN'] = '121212121212120aaa'
  } 
  //是否为pc端请求
  //config.headers['IS-PC'] = Utils.baseUtil.isPcOrMobile() == 'pc'
  config.headers['IS-PC'] = true;
  // APPF_SCGL-bdydother, APPF_SCGL-ts, APPF_SCGL-bdyx
  config.headers['APK-CODE'] = 'APPF_SCGL-bdydother'
  config.headers['APK-VERSION'] = 65
  config.headers['IMEI'] = Utils.deviceInfo.getDeviceIMEL()
  //是否加密,无加密字段默认为false 不加密
  config.headers['ENCRYPT'] = false
  if (loginUrl) {
    config.headers['ZIP'] = 0
    return config
  }

  //如果是pc上或登录接口不走压缩
  //if (!isEncryptCheck(config)) {
  if (true) {
    //console.log('直接返回,不走加密压缩')
    config.headers['ZIP'] = 0
    return config
  } else {
    // 移动端默认加密
    config.headers['ENCRYPT'] = true
    console.log('准备加密')
    var encryptCheck = {
      encrypt: config.headers.ENCRYPT,
      data: config.data
    }
    const salt = localStorage.getItem("salt") || keys
    var getKeys = null
    if (typeof salt == 'string') {
      getKeys = JSON.parse(salt)
    } else {
      getKeys = salt
    }
    if (getKeys != null) {
      encryptCheck.salt = getKeys.salt;
      encryptCheck.pubKey = getKeys.pubKey;
      encryptCheck.priKey = getKeys.priKey;
    }
    Gzip.zip(function (data) {
      console.log('Gzip 执行结果' + JSON.stringify(data))
      // 是否压缩根据内容大小判定，bytes.length = 600 压缩，否则不压缩
      // 数据压缩则 设置压缩：1 ，未压缩则设置 不压缩：0
      config.headers['ZIP'] = data.zip ? 1 : 0
      config.data = data.bstr; // 加密或加密压缩后数据
    }, function (err) {
      console.log("压缩失败：" + JSON.stringify(err));
    }, encryptCheck);
  }

  console.log('请求参数' + JSON.stringify(config.data))
  console.log('请求headers参数' + JSON.stringify(config.headers))
  return config
}, error => {
  return Promise.reject(error)
})

/* 响应拦截 */
service.interceptors.response.use(response => {
  // console.log('response '+JSON.stringify(response))
  if (!isEncryptCheck(response.config)) {
    //在pc端时不加密压缩，直接返回
    // 下载时需要返回整个response
    if (response.config.url.indexOf("downLoadAttachment") > -1) {
    // if (response.config.url.indexOf("appGetFileByUUID") > -1 ||
    //   response.config.url.indexOf("getBigFileByUUID") > -1) {
      return response
    } else {
      return response.data
    }
  } else {
    const salt = localStorage.getItem("salt") || keys
    var getKeys = null
    if (typeof salt == 'string') {
      getKeys = JSON.parse(salt)
    } else {
      getKeys = salt
    }
    let encryptCheck = {
      salt: getKeys.salt,
      data: response.data.pkg,
      encrypt: true,
      zip: response.data.headers && response.data.headers.ZIP || 0
    }

    // 返回数据解压缩\解密
    return unzipResponse(encryptCheck)
  }
}, error => {
  console.log('接口异常:' + JSON.stringify(error))
  if (error.response) {
    switch (error.response.status) {
      case 401:
        Notify({ type: 'danger', message: '未授权,请重新登录', duration: 4000 })
        //执行退出事件
        break
      case 403:
        Notify({ type: 'danger', message: '拒绝访问', duration: 4000 })
        break
      case 500:
        Notify({ type: 'warning', message: '后台服务异常,请联系管理员!', duration: 4000 })
        //执行登录事件，跳转至登录页
        break
      case 404:
        Notify({ type: 'warning', message: '很抱歉,资源未找到!', duration: 4000 })
        break
      case 504:
        Notify({ type: 'danger', message: '网络超时', duration: 4000 })
        break
      default:
        Notify({ type: 'danger', message: error.response.statusText, duration: 4000 })
    }
  } else {
    if (error.message == "Network Error") {
      Notify({ type: 'danger', message: "请检查网络是否连接正常!", duration: 4000 })
    } else {
      Notify({ type: 'danger', message: error.message, duration: 4000 })
    }
  }
  return Promise.reject(error)
})

// 检查是否需要加密压缩
const isEncryptCheck = function (config) {
  // 是否加密压缩
  let isCheck = false, url = config.url
  // pc端、登录、上传、下载 getKeys 不走加密压缩
  if (Utils.baseUtil.isPcOrMobile() == 'pc' ||
    url.indexOf('appLogin') > -1 ||
    url.indexOf('getKeys') > -1 ||
    url.indexOf("appUpLoadFile") > -1 ||
    url.indexOf("getBigFileByUUID") > -1 ||
    url.indexOf("appGetFileByUUID") > -1) {
    isCheck = false
  } else {
    isCheck = true
  }

  return isCheck
}

/**
 * 返回数据进行解压或解压解密
 * @param {String} encryptCheck 加密串
 * @return resonse
 */
const unzipResponse = (encryptCheck) => {
  // 默认返回数据对象
  let decryptData = {
    code: 0,
    success: false,
    data: {},
    msg: '无数据'
  }
  Gzip.unzip(function (unzipData) {
    console.log("response-文本请求解压成功：" + JSON.stringify(unzipData));
    let result = typeof unzipData == 'string' && JSON.parse(unzipData)
    decryptData.success = result.success
    decryptData.code = result.code
    decryptData.data = result.data
    decryptData.msg = result.msg
  }, function (unzipErr) {
    console.log("response-文本请求解压失败：" + JSON.stringify(unzipErr));
    decryptData.msg = unzipErr
  }, encryptCheck)

  return decryptData
}

/**
 * get封装
 * @param {String} url
 * @param {Object} params
 * @param {Object} config
 */
const get = (url, params, config = {}) => {
  let conf = Object.assign({
    url,
    method: 'get',
    params: params
  }, config)
  return service(conf).then(respnose => {
    return none(respnose)
  })
}

// add 调用安卓端请求(Post,upload,download) start
/**
 * android post封装
 * @param {String} url
 * @param {Object} params
 */
async function javaPost(url, params) {
  return new Promise((resolve, reject) => {
    var paramsData = {
      url: url,
      data: params
    }
    tpf.platformclient.httpRequest(paramsData, function (data) {
      console.log('javaPost成功返回' + JSON.stringify(data))
      // if (typeof data == 'string') {
      //   data = JSON.parse(data)
      // }
      resolve(data)
    }, function (err) {
      console.log('javaPost失败返回' + JSON.stringify(err))
      reject(err)
    })
  })
}

/**
 * android 下载封装
 * @param {String} url
 * @param {Object} params
 */
async function javaDownload(url, params) {
  return new Promise((resolve, reject) => {
    var paramsData = {
      url: url,
      data: params
    }
    tpf.platformclient.fileDownload(paramsData, function (data) {
      console.log('javaDownload成功返回' + JSON.stringify(data))
      if (typeof data == 'string') {
        data = JSON.parse(data)
      }
      resolve(data)
    }, function (err) {
      console.log('javaDownload失败返回' + JSON.stringify(err))
      reject(err)
    })
  })
}

/**
 * android 上传封装
 * @param {String} url
 * @param {Object} params
 */
async function javaUpload(url, params) {
  return new Promise((resolve, reject) => {
    var paramsData = {
      url: url,
      data: params
    }
    tpf.platformclient.fileUpload(paramsData, function (data) {
      console.log('javaUpload成功返回' + JSON.stringify(data))
      if (typeof data == 'string') {
        data = JSON.parse(data)
      }
      resolve(data)
    }, function (err) {
      console.log('javaUpload失败返回' + JSON.stringify(err))
      reject(err)
    })
  })
}
// add 调用安卓端请求(Post,upload,download) end

/**
 * post封装 ，兼容处理在安卓端请求
 * @param {String} url
 * @param {Object} data
 * @param {Object} config
 */
const post = (url, data, config) => {
  //在pc端或登录接口，使用axios请求，其它情况走安卓端post请求
  //两者的区别，pc端方式走，需要在request拦截器中对请求参数进行加密处理，在android端走，加密处理在安卓中已经处理
  if (Utils.baseUtil.isPcOrMobile() == 'pc' || url.indexOf('appLogin') > -1) {
    //pc
    let conf = Object.assign({
      url,
      method: 'post',
      data: data
    }, config)
    return service(conf).then(respnose => {
      return none(respnose)
    }).catch(err => {
      return Promise.reject(err)
    })
  } else {
    //移动端
    return javaPost(url, data)
  }
}

/**
 * @param {Object} config
 */
const ajax = (config) => {
  return service(config).then(respnose => {
    return none(respnose)
  })
}

// 上传文件
const uploadFile = (formData, config = {}) => {
  //var url = 'bdydzy-ptmo-pub/web/public/v2/appUpLoadFile'
  var url = '/app/deviceMaintain/maintain-record/uploadPic'
  let conf = {
    url,
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    ...config
  }
  console.log("打印userid：" + formData.get("userId"))
  return service.post(url, formData, conf).then(respnose => {
    return Promise.resolve(respnose)
  }).catch(err => {
    return Promise.reject(err)
  })
}
// 上传文件 缺陷
const uploadFileFile = (formData, config = {}) => {
  //var url = 'bdydzy-ptmo-pub/web/public/v2/appUpLoadFile'
  var url = '/fsDefect/defectService/uploadAttachment'
  let conf = {
    url,
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    ...config
  }
  console.log("打印userid：" + formData.get("userId"))
  return service.post(url, formData, conf).then(respnose => {
    return Promise.resolve(respnose)
  }).catch(err => {
    return Promise.reject(err)
  })
}

/**
 * downloadFile封装
 * @param {String} url
 * @param {Object} data
 * @param {Object} config
 */
const downloadFile = (url, formData, config = {}) => {
  let conf = {
    url,
    headers: {
      'contentType': 'application/octet-stream'
    },
    ...config
  }
  return service.post(url, formData, conf).then(response => {
    let a = document.createElement("a");
    let url = window.URL.createObjectURL(new Blob([response.data]));
    a.href = url;
    let fileName = response.headers && response.headers.filename
    // console.log("文件名",response.headers)
    // console.log("文件名2",response.headers.fileName)
    a.download = fileName;
    a.click();
    window.URL.revokeObjectURL(url);
    return Promise.resolve(response)
  }).catch(err => {
    return Promise.reject(err)
  })
}

/**
 *  封装download方法
 *  @param {array} data
 *  @return {Promise} (Promise)
 */
export function downloadFileres(url, formData,config) {
  return new Promise((resolve, reject) => {
    let conf = {
      url,
      headers: {
        "Content-Type": "application/json; charset=utf-8"
      },
      // ...config
       responseType: "blob" 
    }
    return service.post(url, formData,conf)
      .then(response => {
        console.log(response);
        let url = window.URL.createObjectURL(new Blob([response.data]));
        console.log(url);
        var name = response.headers.filename.split(".")
        var type = name[name.length - 1]
        // let url = Utils.baseUtil.downloadFileblob(response)//
       
        // // 执行完下载事件后，返回响应信息
        resolve({ url: url, type: type })
      }).catch(err => {
        // 异常信息返回
        reject(err)
      })
  })
}
// /**
//  *  封装download方法
//  *  @param {array} data
//  *  @return {Promise} (Promise)
//  */
// export function downloadFileres(url, data = {}) {
//   return new Promise((resolve, reject) => {
//     service.post(url, data, { responseType: "blob" })
//       .then(response => {
//         console.log(response);
//         var name = response.headers.filename.split(".")
//         var type = name[name.length - 1]
//         let url = util.downloadFileblob(response)//
//         // let url= util.fileToBase(response)// 
//         console.log(url);
//         // // 执行完下载事件后，返回响应信息
//         resolve({ url: url, type: type })
//       }).catch(err => {
//         // 异常信息返回
//         reject(err)
//       })
//   })
// }

/**
 * 错误code处理
 * @param {Object} respnose
 */
const none = (response) => {
  if (response) {
    return Promise.resolve(response)
  }
}

export default {
  get,
  post,
  ajax,
  uploadFile,
  uploadFileFile,
  downloadFile,
  downloadFileres
}
